<script setup lang="ts">
import { AddPark, DetailPark, EditPark, Industry, UpLoadfile } from "@/apis/park";
import type { AddParkObj, IndustryList } from "@/types/Park";
import { CircleCheck, Upload } from "@element-plus/icons-vue";
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type UploadRawFile,
  type UploadRequestOptions,
  type UploadUserFile,
} from "element-plus";
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
const route=useRoute()
const addForm = ref<AddParkObj>({
  name: "", // 企业名称
  legalPerson: "", // 法人
  registeredAddress: "", // 注册地址
  industryCode:undefined , // 所在行业
  contact: "", // 企业联系人
  contactNumber: "", // 联系人电话
  businessLicenseUrl: "", // 营业执照url
  businessLicenseId: null, // 营业执照id
  id:undefined
});
const rules = ref<FormRules<AddParkObj>>({
  name: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
  legalPerson: [{ required: true, message: "请输入法人", trigger: "blur" }],
  registeredAddress: [
    { required: true, message: "请输入注册地址", trigger: "blur" },
  ],
  industryCode: [{ required: true, message: "请选择行业", trigger: "change" }],
  contact: [{ required: true, message: "请输入企业联系人", trigger: "blur" }],
  contactNumber: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
  ],
  businessLicenseUrl: [
    { required: true, message: "请上传营业执照", trigger: "change" },
  ],
});
const Industrylist = ref<IndustryList[]>([]);
const ruleForm = ref<FormInstance>();
// 行业列表
const industry = async () => {
  const res = await Industry();
  // console.log('res',res);
  Industrylist.value = res.data;
};
// 上传文件
const UploadFile = async (obj: UploadRequestOptions) => {
  const fd = new FormData();
  fd.append("file", obj.file);
  fd.append("type", "businessLicense");
  const res = await UpLoadfile(fd);
  //  console.log('res',res);
  addForm.value.businessLicenseUrl = res.data.url;
  addForm.value.businessLicenseId = res.data.id;
  ruleForm.value?.validateField('businessLicenseUrl')
  return res.data.url;
};
const removeUpload = () => {
  // 主动清楚营业执照 url 和 id
  addForm.value.businessLicenseUrl = ''
  addForm.value.businessLicenseId = null
  // 主动触发校验，提醒用户
  ruleForm.value?.validateField('businessLicenseUrl')
}
const fileList = ref<UploadUserFile[]>([]);
onMounted(() => {
  if(route.params.id){
    Detail()
  }
  industry();
});
// 编辑获取详情
const Detail=async()=>{
  const res=await DetailPark(route.params.id as string)
 const {name,legalPerson,businessLicenseId,businessLicenseUrl,contact,contactNumber,industryCode,registeredAddress,id}=res.data
 addForm.value={
  name,
  legalPerson,
  businessLicenseId,
  businessLicenseUrl,
  contact,
  contactNumber,
  industryCode,
  registeredAddress,
  id
 }
 fileList.value=[{
  name:name,
  url:businessLicenseUrl
 }]
}

// 判断文件的大小和类型
const beforeUpload = (file:UploadRawFile) => {
if(file.size >5*1024*1024){
  ElMessage.error('文件大小不能超过5M');
  return false

}else if(file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/jpg'){
  ElMessage.error('请上传jpg/png格式的图片');
  return false
}else{
  ElMessage.success('上传成功');
  return true
}
}
const router=useRouter()
const IsLoading = ref(false);
const Add =async () => {
  try {
   await ruleForm.value?.validate()
      IsLoading.value = true;
    const res=await AddPark(addForm.value);
    if(res.code === 10000){
      ElMessage.success("添加成功");
      router.back();
    }else{
      ElMessage.error(res.msg);
      IsLoading.value = false;
    }
  } catch{
    IsLoading.value = false;
  }

};
// 清空表单
const Onclear = () => {
  ruleForm.value?.resetFields();
  fileList.value = [];
  addForm.value.businessLicenseId =null
};
const Edit=async()=>{
 const res = await EditPark(addForm.value)
 if(res.code === 10000){
  ElMessage.success("修改成功");
  router.back();
}else{
  ElMessage.error(res.msg);
  IsLoading.value = false;
}
}

</script>

<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header v-if="$route.params.id" content="编辑企业" @back="$router.back()" />
      <el-page-header v-else content="添加企业" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form
            ref="ruleForm"
            label-width="100px"
            :rules="rules"
            :model="addForm"
          >
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode" clearable>
                <el-option
                  v-for="item in Industrylist"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" maxlength="11"/>
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
              <el-upload
                :http-request="UploadFile"
                :limit="1"
                list-type="picture"
                v-model:file-list="fileList"
                :before-upload="beforeUpload"
                @remove="removeUpload"
              >
              <!--   accept="..png, .jpg, .jpeg"可以限制类型 -->
                <el-button
                  v-if="fileList.length === 0"
                  type="primary"
                  :icon="Upload"
                  >点击上传</el-button>
                <el-button v-else type="success" disabled :icon="CircleCheck">已上传</el-button>
                <template #tip>
                  <div>
                    上传的jpg/png文件不超过 500KB.
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            {{ addForm }}
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="Onclear">重置</el-button>
        <el-button type="primary" v-if="$route.params.id" @click="Edit" :loading="IsLoading">修改</el-button>
        <el-button type="primary" v-else @click="Add" :loading="IsLoading">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
